#include "stdafx.h"
#include "ICanny.h"
//OpenCV libs
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv/cv.h"

const char * const ICanny::FunctionNameICanny = "Edge Detection - Canny";

ICanny::ICanny(void) 
{
	_fnApi.SetFunctionName(ICanny::FunctionNameICanny);
	_fnApi.SetFunctionDescription("This function finds edges in an image using Canny algorithm.");
									//inputs
	_fnApi.AddParamDef(new ProcParamDefDouble(0, "LowThreshold", "Sets the first threshold for the hysteresis procedure", ProcParamDef::input, 0, 100 ));
	_fnApi.AddParamDef(new ProcParamDefDouble(1, "HighThreshold", "Sets the second threshold for the hysteresis procedure", ProcParamDef::input, 0, 100 ));
	_fnApi.AddParamDef(new ProcParamDefInt(2, "SobelAperture", "Sets the Aperture size for the Sobel() operator - default = 3", ProcParamDef::input, 0, 6 ));
	_fnApi.AddParamDef(new ProcParamDefInt(3, "L2gradient ", "Put '1' to use L2 norm (might not work if you put in big values), '0' to use the faster L1 norm instead (recommended)", ProcParamDef::input, 0, 1 ));
									//outputs
	_fnApi.AddParamDef(new ProcParamDefInt(0, ProcParam::attribOutputParamNameResult, "0 is success", ProcParamDef::output, 0, 1));

	_fnApi.Validate();
}


ICanny::~ICanny(void)
{

}


bool ICanny::Process(ImageProcStep *step, bool DebugMode)
{	
	bool rc = false;
	if ((step != '\0') && (step->IsValid()))
	{
		
		ProcParamDouble *threshold1 = dynamic_cast<ProcParamDouble *>(step->GetInputs()->GetParam(0));	//Check the Param number
		ProcParamDouble *threshold2 = dynamic_cast<ProcParamDouble *>(step->GetInputs()->GetParam(1));
		ProcParamInt *aperture = dynamic_cast<ProcParamInt *>(step->GetInputs()->GetParam(2));
		ProcParamInt *IntGradient = dynamic_cast<ProcParamInt *>(step->GetInputs()->GetParam(3));
		bool BoolGradient = false;
		if (int(IntGradient->GetValue() > 0))
			BoolGradient = true;
		if  (threshold1 != '\0' && threshold2 != '\0' && aperture != '\0' && IntGradient != '\0')
		{
			cv::Mat output;
			cv::Mat input = cv::imread(step->GetIntermediateImagePathFilename(), 0);	//0 loads grayscale
			
			cv::Canny(input, output, double(threshold1->GetValue()), double(threshold2->GetValue()), int(aperture->GetValue()), BoolGradient);

			cv::imwrite(step->GetIntermediateImagePathFilename(), output);

			input.release();
			output.release();
			rc = true;
		}
	}
	return rc;
}

